package com.linkage.common.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.SetBucketCORSRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Slf4j
public class OSSUtils {

    private static final String ENDPOINT="oss-cn-beijing.aliyuncs.com";

    private static final String ACCESSKEY_ID="LTAIdzjR2sk2luMG";
    private static final String ACCESSKEY_SECRET="y0GKku9Mh0mMKKr02jdmzlP2tWO7Mp";
    private static final String BUCKET_NAME="jingbaoliandong";

    /**
     * 上传单个文件
     * @param file
     * @param folder
     * @return
     */
    public static String uploadFileSingle(MultipartFile file,String folder){
        OSS oss = new OSSClientBuilder().build(ENDPOINT,ACCESSKEY_ID,ACCESSKEY_SECRET);
        if(!oss.doesBucketExist(BUCKET_NAME)){
            oss.createBucket(BUCKET_NAME);
        }
//        bucketConfig(oss);
        String url = "";
        try {
            String newFileKey = putObject(folder,file,oss);
            url = getUrl(oss,newFileKey);
        }catch (Exception e){
            log.error("上传失败",e);
            oss.shutdown();
        }finally {
            oss.shutdown();
        }
        return url;
    }

    /**
     * 上传多个文件
     * @param files
     * @param folder
     * @return
     */
    public static List uploadFileSingle(MultipartFile[] files, String folder){
        OSS oss = new OSSClientBuilder().build(ENDPOINT,ACCESSKEY_ID,ACCESSKEY_SECRET);
        if(!oss.doesBucketExist(BUCKET_NAME)){
            oss.createBucket(BUCKET_NAME);
        }
        List<String> urls = new ArrayList<>();
//        bucketConfig(oss);
        Arrays.stream(files).forEach( file ->{
            try {
                String newFileKey = putObject(folder,file,oss);
                urls.add(getUrl(oss,newFileKey));
            }catch (Exception e){
                log.error("上传失败",e);
                oss.shutdown();
            }
        });
        return urls;
    }

    /**
     * 配置bucket
     * @param oss
     */
    private static void bucketConfig(OSS oss){
        SetBucketCORSRequest corsRequest = new SetBucketCORSRequest(BUCKET_NAME);
        SetBucketCORSRequest.CORSRule rule = new SetBucketCORSRequest.CORSRule();
        //指定允许跨域请求的来源
        rule.addAllowdOrigin("*");
        //指定允许的跨域请求方法(GET/PUT/DELETE/POST/HEAD)
        rule.addAllowedMethod("POST");
        //控制在OPTIONS预取指令中Access-Control-Request-Headers头中指定的header是否允许。
        rule.addAllowedHeader("*");
        corsRequest.addCorsRule(rule);
        oss.setBucketCORS(corsRequest);
        oss.setBucketAcl(BUCKET_NAME, CannedAccessControlList.PublicReadWrite);
    }

    /**
     * 上传到oss服务器
     * @param folder
     * @param file
     * @param oss
     * @return
     * @throws Exception
     */
    private static String putObject(String folder, MultipartFile file, OSS oss) throws Exception{
        String[] fileName = file.getOriginalFilename().split("\\.");
        String timestamp = String.valueOf(System.currentTimeMillis());
        String newFileKey = folder+timestamp+"."+fileName[1];
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentLength(file.getInputStream().available());
        objectMetadata.setCacheControl("no-cache");
        objectMetadata.setHeader("Pragma", "no-cache");
        objectMetadata.setContentType(getContentType(fileName[1]));
        oss.putObject(BUCKET_NAME, newFileKey, file.getInputStream());
        return newFileKey;
    }

    /**
     * Description: 判断OSS服务文件上传时文件的contentType
     *
     * @param FilenameExtension 文件后缀
     * @return String
     */
    public static String getContentType(String FilenameExtension) {
        if (FilenameExtension.equalsIgnoreCase("bmp")) {
            return "image/bmp";
        }
        if (FilenameExtension.equalsIgnoreCase("gif")) {
            return "image/gif";
        }
        if (FilenameExtension.equalsIgnoreCase("jpeg") ||
                FilenameExtension.equalsIgnoreCase("jpg") ||
                FilenameExtension.equalsIgnoreCase("png")) {
            return "image/jpeg";
        }
        if (FilenameExtension.equalsIgnoreCase("html")) {
            return "text/html";
        }
        if (FilenameExtension.equalsIgnoreCase("txt")) {
            return "text/plain";
        }
        if (FilenameExtension.equalsIgnoreCase("vsd")) {
            return "application/vnd.visio";
        }
        if (FilenameExtension.equalsIgnoreCase("pptx") ||
                FilenameExtension.equalsIgnoreCase("ppt")) {
            return "application/vnd.ms-powerpoint";
        }
        if (FilenameExtension.equalsIgnoreCase("docx") ||
                FilenameExtension.equalsIgnoreCase("doc")) {
            return "application/msword";
        }
        if (FilenameExtension.equalsIgnoreCase("xml")) {
            return "text/xml";
        }
        return "image/jpeg";
    }

    /**
     * 获得url链接
     *
     * @param key
     * @return
     */
    public static String getUrl(OSS oss,String key) {
        // 设置URL过期时间为10年  3600l* 1000*24*365*10
        Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 10);
        // 生成URL
        URL url = oss.generatePresignedUrl(BUCKET_NAME, key, expiration);
        if (url != null) {
            return url.toString();
        }
        return null;
    }
}
